import { useEffect, useState } from 'react';
import { useDebounce } from '@cfe/hooks';
import { Alert, Spin } from 'antd';
import { decamelizeKeys } from 'humps';

import { numberWithThousands } from '@/utils/number';
import { requestWithoutCache } from '@/utils/request';

import DraggableList from './DraggableList';

const FilterItem = ({ onChange, initialValue }) => {
  const [filter, setFilter] = useState();
  const [coverage, setCoverage] = useState();
  const [loading, setLoading] = useState(false);
  const filterString = JSON.stringify(filter);

  const debouncedRequestCoverage = useDebounce(() => {
    if (!filter) return;
    setLoading(true);
    requestWithoutCache(`/api/dmp/crowd/coverage`, {
      body: JSON.stringify(decamelizeKeys(filter)),
      method: 'POST',
    })
      .then((res) => {
        setLoading(false);
        const {
          data: { coverage },
        } = res;
        setCoverage(coverage);
      })
      .catch(() => {});
  }, 300);

  useEffect(() => {
    debouncedRequestCoverage();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterString]);

  if (!initialValue) return null;
  return (
    <div>
      <DraggableList
        onChange={(value) => {
          onChange?.(value);
          setFilter(value);
        }}
        initialValue={initialValue}
      />
      <p style={{ marginTop: '10px', marginLeft: '30px' }}>
        <Alert
          message={
            loading ? (
              <Spin />
            ) : (
              `覆盖人数：${coverage ? numberWithThousands(coverage) : 0}`
            )
          }
          type="info"
          showIcon
        />
      </p>
    </div>
  );
};

export default FilterItem;
